- Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathHeap.java
120 lines (86 loc) Β· 2.35 KB
/
Heap.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
packagesection17_Heap;
importjava.util.ArrayList;
//import java.util.Collections;
publicclassHeap {
ArrayList<Integer> data = newArrayList<>();
publicvoidadd(intitem) {
data.add(item);
upheapify(data.size() - 1);
}
privatevoidupheapify(intchildIndex) {
intparentIndex = (childIndex - 1) / 2;
if (data.get(childIndex) < data.get(parentIndex)) {
// Collections.swap(data, childIndex, parentIndex);
this.swap(childIndex, parentIndex);
upheapify(parentIndex);
}
}
privatevoidswap(inti, intj) {
intithVal = data.get(i);
intjthVal = data.get(j);
data.set(i, jthVal);
data.set(j, ithVal);
}
publicvoiddisplay() {
System.out.println(data);
}
publicintsize() {
returnthis.data.size();
}
publicbooleanisEmpty() {
returnthis.size() == 0;
}
publicintremove() throwsException {
if (this.size() == 0)
thrownewException("No elements to remove...");
intremovedItem = data.get(0);
this.swap(0, this.size() - 1);
data.remove(this.size() - 1);
downheapify(0);
returnremovedItem;
}
// clean code
publicvoiddownheapify(intpi) {
intlci = 2 * pi + 1;
intrci = 2 * pi + 2;
intminIndex = pi;
if (lci < this.size() && data.get(lci) < data.get(minIndex))
minIndex = lci;
if (rci < this.size() && data.get(rci) < data.get(minIndex))
minIndex = rci;
if (minIndex != pi) {
swap(minIndex, pi);
downheapify(minIndex);
}
}
/*
private void downheapify2(int parentIndex) {
int leftChildIndex = (2 * parentIndex) + 1;
int rightChildIndex = (2 * parentIndex) + 2;
if (leftChildIndex >= this.size() && rightChildIndex >= this.size())
return;
int leftChild = -1, rightChild = -1;
int parentData = data.get(parentIndex);
if (leftChildIndex < this.size())
leftChild = data.get(leftChildIndex);
if (rightChildIndex < this.size())
rightChild = data.get(rightChildIndex);
if (leftChild == -1 && rightChild == -1)
return;
if (parentData > leftChild || parentData > rightChild) {
if (rightChild == -1) {
this.swap(parentIndex, leftChildIndex);
downheapify2(leftChildIndex);
} else {
int minVal = Math.min(leftChild, rightChild);
int minIndex = minVal == leftChild ? leftChildIndex : rightChildIndex;
this.swap(parentIndex, minIndex);
downheapify2(minIndex);
}
}
}
*/
publicintget() {
returnthis.data.get(0);
}
}